<?php

class Ws{

    const HOST = '0.0.0.0';
    const PORT = '10009';

    private $ws = null;

    public function __construct()
    {
        $this->ws = new \Swoole\WebSocket\Server(self::HOST, self::PORT);

        $this->ws->set([
            'worker_num' => 2,
            'task_worker_num' => 2 //设置异步任务的工作进程数量
        ]);
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);
        $this->ws->on('close', [$this, 'onClose']);

        $this->ws->start();
    }

    /**
     * 监听客户端连接
     * @param $ws
     * @param $request
     */
    function onOpen($ws, $request){
        echo "新连接: ".$request->fd.PHP_EOL;
    }

    /**
     * 监听客户端消息
     * @param $ws
     * @param $frame
     */
    function onMessage($ws, $frame){
        echo "新数据: ".$frame->data.PHP_EOL;

        //耗时操作交给task执行
        $data = [
          'task'=>1,
          'fd' =>$frame->fd
        ];
        $ws->task($data);

        //给客户端返回数据
        $ws->push($frame->fd, "服务器时间: ".time());
    }

    /**
     * 执行耗时任务
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     * @return string
     */
    function onTask($serv, $taskId, $workerId, $data){

        echo '开始执行任务: ';
        print_r($data);

        //休眠十秒, 模拟耗时操作
        sleep(10);

        //告诉worker,任务执行成功
        return "task success";

    }

    /**
     * 任务执行结束
     * @param $serv
     * @param $taskId
     * @param $data
     */
    function onFinish($serv, $taskId, $data){
        echo '任务执行结束: '.$taskId.', '.$data;
    }

    /**
     * 断开连接
     * @param $ws
     * @param $fd
     */
    function onClose($ws, $fd){
        echo "连接关闭: ".$fd.PHP_EOL;
    }

}

new Ws();




